import { useRef, useEffect } from "react";
import { useNavigate } from "react-router-dom";

function StudentDetail(props) {
    const { stuinfo } = props;
    const formRef = useRef(null);
    let navigate = useNavigate();

    //　空表单或获取学生信息后，给表单设置初始值
    useEffect(() => {
        if (!formRef.current) return;

        if (!stuinfo) return;

        const elements = formRef.current.elements;

        elements.stu_no.value = stuinfo.stu_no ?? "";
        elements.stu_name.value = stuinfo.stu_name ?? "";
        elements.gender.value = stuinfo.gender ?? "";
        elements.enrolled.value = stuinfo.enrolled ?? "";
    }, [stuinfo]);

    const saveAction = async () => {
        if (!formRef.current) return;

        const elements = formRef.current.elements;
        let data = {
            stu_sn: stuinfo.stu_sn,
            stu_no: elements.stu_no.value,
            stu_name: elements.stu_name.value,
            gender: elements.gender.value,
            enrolled: elements.enrolled.value,
        };

        let url, http_method;
        if (data.stu_sn !== null) {
            // 更新学生记录信息
            url = `/api/student/${stuinfo.stu_sn}`;
            http_method = "PUT";
        } else {
            // 新建学生记录
            url = `/api/student`;
            http_method = "POST";
        }

        // 向服务器发送请求
        let response = await fetch(url, {
            method: http_method,
            headers: {
                "Content-Type": "application/json;charset=utf-8",
            },
            body: JSON.stringify(data), // 将data对象序列化为JSON的字符串
        });

        // 检查返回的响应信息
        // TODO: 如果业务逻辑出错，需要向用户提示错误信息。
        if (!response.ok) {
            console.error(response);
        }
        
        navigate("/student/list");
    };

    const deleteAction = async () => {
        let response = await fetch(`/api/student/${stuinfo.stu_sn}`, {
            method: "DELETE",
        });

        if (!response.ok) {
            console.error(response);
            return;
        }

        navigate("/student/list");
    };


    return (
        // <> </> 嵌套JSX片段
        <>
            <div className="paper-body">
                <form ref={formRef}>
                    <div className="field">
                        <label>学号: </label>
                        <input type="text" name="stu_no" />
                    </div>
                    <div className="field">
                        <label>姓名: </label>
                        <input type="text" name="stu_name" />
                    </div>
                    <div className="field">
                        <label>性别: </label>
                        <div className="radio-choices">
                            <span className="option">
                                男
                                <input type="radio" name="gender" value="m" />
                            </span>
                            <span className="option">
                                女
                                <input type="radio" name="gender" value="f" />
                            </span>
                        </div>
                    </div>
                    <div className="field">
                        <label>入学时间: </label>
                        <input type="date" name="enrolled" />
                    </div>
                </form>
            </div>
            <div className="paper-footer">
                <div className="btns">
                    <button className="btn" onClick={deleteAction}>
                        删除
                    </button>
                    <button className="btn" onClick={saveAction}>
                        保存
                    </button>
                    <button
                        className="btn"
                        onClick={() => {
                            navigate("/student/list");
                        }}
                    >
                        返回
                    </button>
                </div>
            </div>
        </>
    );
}

export default StudentDetail;
